# -*- coding: utf-8 -*-

import requests
import json
import hashlib
import time
import _thread
import random
from urllib.parse import urlencode

"""
多个用户开播
Created on Tue Jul 27 12:41:39 2021

@author: Administrator
"""

def getHtml(url, paramss, type = "post", userMap= {}):
    try:
        header = {'Content-Type': 'application/json; charset=UTF-8',
            "app_type": "1",
            "version": "1.21.38-test210617-1" }
        if("null" != userMap.get("token","null")):
            header["Authorization"] = userMap["token"]


        # params:{uid=40076, oid=43296, key=43296, type=0, gid=43, gift_type=1, num=1, plat=android, yzt=56070fae6b37ad772ae6ed994a082038}
        # 代理
        # prox = {}
        
        if("post" == type):
            if ("null" != userMap.get("yzt", "null")):
                url += userMap["yzt"]
            print("================  请求地址和参数  ======================")
            print(url)
            print(paramss)
            print("========================================================")
            data = requests.post(url, data=paramss, headers=header, timeout=2)
        else:
            data = requests.get(url, data=paramss, headers=header, timeout=2)
        data.encoding = "utf-8"
        # print(data.text)
        return data.text
    except Exception as e:
        print(str(e))
        return "异常"


# 有的接口需要yzt参数
def getYzt(mydata):
    mydata = mydata + "a4be9f32637e217fb8dbbcae75759fb3"
    return hashlib.md5(mydata.encode(encoding='UTF-8')).hexdigest()


# Url参数添加验证码
def getUrlYzt(account, password):
    cdt = str(round(time.time() * 1000))
    mydata = account + password + cdt
    yzt = hashlib.md5(mydata.encode(encoding='UTF-8')).hexdigest()
    s_act = account + "_" + password + "_" + yzt
    return "?act="+s_act+"&cdt="+cdt

"""
==============================================================================
    实际用户API接口调用
==============================================================================
"""

def generate_random_str(randomlength=16):
  """
  生成一个指定长度的随机字符串
  """
  random_str =''
  base_str ='ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
  length =len(base_str) -1
  for i in range(randomlength):
    random_str +=base_str[random.randint(0, length)]
  return random_str
# 登录将登录数据放在文件中
def login(phone, code="831246"): # 831246 202088
    # phone = "18782927715"
    # paramss =  '{"uid":"40026", "amount":"9800"}'

    paramss = {"code": code, "cell": phone, "did": generate_random_str(),
               "mac": "3C:86:D1:5A:EB:" + str(random.randint(10, 99)), "dev": "1", "plat": "vivo_V1928A", "ver": "28_9",
               "sys": "androidphone", "sver": "1.0.5", "firm": "9",
               "mart": "android", "token": "",
               "ip": "192.168." + str(random.randint(3, 200)) + "." + str(random.randint(5, 200)), "source": "and-0",
               "yzt": getYzt(phone), "lat": "30.554378",
               "lng": "104.07132", "city": "510100", "cityname": "成都市",
               "state": "510000", "statename": "四川省"}
    dd = str(paramss)
    # print(dd)
    par = dd.encode("utf-8").decode("latin-1")
    data = getHtml(URLHOST+"yonghu/celllogin", par)
    print(data)

    userMaps = {}
    try:
        json_to_python = json.loads(data)
        token = json_to_python['Data']["token"]
        uid = json_to_python['Data']["uid"]
        cell = json_to_python['Data']["cell"]
        pwd = json_to_python['Data']["password"]
        yzt = getUrlYzt(cell, pwd)

        userMaps = {"token": token, "uid": uid, "yzt": yzt}
    except Exception as e1:
        print("===json 解析出错:" + str(e1))
    return userMaps


# 验证码
# def getCode(cell):
#     paramss = {"cell": cell, "yzt": getYzt(cell)}
#     text = URLHOST + "yonghu/getloginsms"+"?cell="+cell +"&yzt="+getYzt(cell)
#     response = getHtml(text, "", "get")
#     print(response)


# 送礼物
def giftsend(oid, gid, num, userMap):
    # gift_type == 1 经典  3 背包
    paramss = {"uid": userMap["uid"], "oid": oid, "key": oid, "type": "0", "gid": gid, "gift_type": "1", "num": num,
               "plat": "android", "yzt": getYzt(userMap["uid"])}
    text = URLHOST + "zhibo/addgiftroom"
    rspMsg = getHtml(text, json.dumps(paramss), "post", userMap)
    # print(rspMsg)
    global sendGiftErrorNum
    global sendGiftOK
    try:
        json_to_python = json.loads(rspMsg)
        print(json_to_python["ErrorMessage"])
        state = json_to_python['IsError']
        if(state == 0):
            sendGiftOK += 1
        else:
            sendGiftErrorNum = sendGiftErrorNum + 1
    except Exception as e1:
        print("===json 解析出错:" + str(e1))


# 加入房间
def joinRoom(userMap, oid):
    paramss = {"uid": userMap["uid"], "oid": oid}
    text = URLHOST + "zhibo/joinchatroom"
    print("=========join======"+getHtml(text, json.dumps(paramss), "post", userMap))

# 送礼失败次数
sendGiftErrorNum = 0
sendGiftOK = 0
#  73   幸运星    74 魔法棒  75 水晶  76 灯
# ======================================直播心跳任务循环
def 线程送礼物任务(val, userMap, oid):
    print(val)
    joinRoom(userMap, oid)
    gifts = [73, 74, 75, 76]
    num = [1, 10, 99, 520]
    for i in range(0, 10000):
        giftsend(oid, gifts[random.randint(0, 2)], num[random.randint(0, 1)], userMap)
        time.sleep(random.randint(1, 3))
    print("=============最终结果：成功次数："+str(sendGiftOK) + "  失败次数：" + str(sendGiftErrorNum))
# ======================================测试线程

# 验证码
def get_code(cell):
    text = URLHOST + "yonghu/getloginsms"+"?cell="+cell + "&yzt=" + getYzt(cell)
    response = getHtml(text, "", "get")
    print(response)


def 送礼物任务():
    # 创建两个线程
    try:
        userList = ["13540124221", "13540124222", "13540124225", "13540124226", "13540124227", "13540124240", "13540124222",]

        # 我的账号送礼物  START
        # 1.获取验证码
        # get_code(userList[0])
        # ALLCODE = "6575"
        # userMap = login(userList[0], ALLCODE)  # 登录

        # get_code(userList[3])
        # get_code(userList[4])
        # ALLCODE = "3337"
        userMap2 = login(userList[2], ALLCODE)  # 登录
        userMap3 = login(userList[3], ALLCODE)  # 登录
        # ALLCODE = "4466"
        userMap4 = login(userList[4], ALLCODE)  # 登录
        # =====  END  END   END



        # userMap1 = login(userList[4], ALLCODE)  # 登录
        # userMap2 = login(userList[2], ALLCODE)  # 登录


        # 模拟用户加入房间
        # for i in range(1, 6):
        #     phone = "1354111110" + str(i)
        #     userM = login(phone, ALLCODE)
        #     joinRoom(userM, "601014")

        # print(userMap)

        # 需要先登录才能执行下面的操作
        # _thread.start_new_thread(线程送礼物任务, ("开始执行任务Thread-0", userList[0],))
        # _thread.start_new_thread(线程送礼物任务, ("开始执行任务Thread-1", userList[1],))
        # _thread.start_new_thread(线程送礼物任务, ("开始执行任务Thread-2", userList[2],))
        # _thread.start_new_thread(线程送礼物任务, ("开始执行任务Thread-3", userList[3],))
        # _thread.start_new_thread(线程送礼物任务, ("开始执行任务Thread-4", userList[4],))
        # _thread.start_new_thread(线程送礼物任务, ("开始执行任务Thread-5", userList[5],))

        # 正式环境我的内部送礼账号
        # _thread.start_new_thread(线程送礼物任务, ("开始执行任务Thread-6-1000", userMap, "601593",))
        # _thread.start_new_thread(线程送礼物任务, ("开始执行任务Thread-6-1", userMap1, "10020",))
        # _thread.start_new_thread(线程送礼物任务, ("开始执行任务Thread-6-1", userMap1, "10015",))
        # _thread.start_new_thread(线程送礼物任务, ("开始执行任务Thread-6-1", userMap2, "600857",))
        _thread.start_new_thread(线程送礼物任务, ("开始执行任务Thread-6-2", userMap2, "601045",))
        _thread.start_new_thread(线程送礼物任务, ("开始执行任务Thread-6-2", userMap3, "601043",))
        _thread.start_new_thread(线程送礼物任务, ("开始执行任务Thread-6-3", userMap4, "600977",))
        # _thread.start_new_thread(线程送礼物任务, ("开始执行任务Thread-6-3", userMap, "600978",))
        # _thread.start_new_thread(线程送礼物任务, ("开始执行任务Thread-6-4", userMap2, "600978",))
        # _thread.start_new_thread(线程送礼物任务, ("开始执行任务Thread-6-4", userMap3, "600978",))

        # _thread.start_new_thread(线程送礼物任务, ("开始执行任务Thread-6-4", userMap1, "600987",))
        # _thread.start_new_thread(线程送礼物任务, ("开始执行任务Thread-6-4", userMap4, "600860",))
        # _thread.start_new_thread(线程送礼物任务, ("开始执行任务Thread-6-4", userMap3, "600987",))
        # _thread.start_new_thread(线程送礼物任务, ("开始执行任务Thread-6-5", userMap, "600989",))
    except:
        print("Error: 无法启动线程")
    while 1:
        pass

# 正式环境
# URLHOST = "http://api.yamizhibo.com/api/"
# ALLCODE = 831246  # 831246
# 测试环境
URLHOST = "http://api.cwoqu.com/api/"
# URLHOST = "http://apitest.cwoqu.com:7076/api/"
ALLCODE = 202088
# =====================================================================================================================
# main 主函数
# ===================c==================================================================================================
if __name__ == '__main__':
    送礼物任务()





